<template>
  <div class="app-container">
    <div id="container" />

    <div class='input-card' v-show="true">
      <div class="input-item">
        <a-button type="primary" size="small" style="width: 90px" @click="startAnimation">
          开始动画
        </a-button>
      </div>

      <div class="input-item">
        <a-button type="primary" size="small" style="width: 90px" @click="pauseAnimation">
          暂停动画
        </a-button>
      </div>

      <div class="input-item">
        <a-button type="primary" size="small" style="width: 90px" @click="resumeAnimation">
          继续动画
        </a-button>
      </div>

      <div class="input-item">
        <a-button type="primary" size="small" style="width: 90px" @click="stopAnimation">
          停止动画
        </a-button>
      </div>

    </div>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出发地" prop="startAddress">
        <el-input
          v-model="queryParams.startAddress"
          placeholder="请输入出发地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="目的地" prop="endAddress">
        <el-input
          v-model="queryParams.endAddress"
          placeholder="请输入目的地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流公司" prop="logisticsCompany">
        <el-input
          v-model="queryParams.logisticsCompany"
          placeholder="请输入物流公司"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="logisticsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="logisticsId" />
      <el-table-column label="出发地" align="center" prop="startAddress" />
      <el-table-column label="目的地" align="center" prop="endAddress" />
      <el-table-column label="发货方" align="center" prop="consigner" />
      <el-table-column label="收货方" align="center" prop="consignee">
        <template v-slot="scope">
          <dict-tag :options="dict.type.sys_warehouse_person" :value="scope.row.consignee"/>
        </template>
      </el-table-column>
      <el-table-column label="货物数量" align="center" prop="goodsNum" />
      <el-table-column label="运输开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运输结束时间" align="center" prop="endeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运输状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0">运输中</el-tag>
          <el-tag v-if="scope.row.status == 1">完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="货物类型" align="center" prop="goodsType" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleClick(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleRk(scope.row)"
          >入库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物流记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出发地" prop="startAddress">
          <el-input v-model="form.startAddress" placeholder="请输入出发地" />
        </el-form-item>
        <el-form-item label="目的地" prop="endAddress">
          <el-input v-model="form.endAddress" placeholder="请输入目的地" />
        </el-form-item>
        <el-form-item label="发货方" prop="consigner">
          <el-input v-model="form.consigner" placeholder="请输入发货方" />
        </el-form-item>
        <el-form-item label="收货方" prop="consignee">
          <el-input v-model="form.consignee" placeholder="请输入收货方" />
        </el-form-item>
        <el-form-item label="货物id" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入货物id" />
        </el-form-item>
        <el-form-item label="货物数量" prop="goodsNum">
          <el-input v-model="form.goodsNum" placeholder="请输入货物数量" />
        </el-form-item>
        <el-form-item label="运输开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="form.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择运输开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="运输结束时间" prop="endeTime">
          <el-date-picker clearable
                          v-model="form.endeTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择运输结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import {listLogistics, getLogistics, delLogistics, addLogistics, updateLogistics, addRk} from "@/api/flow/logistics";
import user from "@/store/modules/user";
// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: 'c07f01e374f57044eed54b1c33087ba1',
}
export default {
  dicts: ['sys_warehouse_person'],
  name: "Logistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流记录表格数据
      logisticsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startAddress: null,
        endAddress: null,
        consigner: null,
        consignee: null,
        goodsId: null,
        goodsNum: null,
        transportType: null,
        startTime: null,
        endeTime: null,
        logisticsCompany: null,
        isFault: null,
        goodsType: null,
        driverId:undefined,
      },
      AMap: null,
      //此处不声明 map 对象，可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
      map: null,
      mouseTool: null,
      lineArr: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      props: {
        visible: Boolean,
      },
      //计算属性 类似于 data 概念
      computed: {},
      //监控 data 中的数据变化
      watch: {
      },
      // 遮罩层
      //import 引入的组件需要注入到对象中才能使用
      components: {},
      startAddress:'',
      endAddress:'',
      marker:null,
      polyline: null,
      speed: '1倍速',
      duration: 500,  // 轨迹回放时间
      percentage: 50,
    };

  },
  created() {
    this.getList();
  },
  methods: {
    handleRk(row){
      addRk(row).then(r=>{
        this.$modal.msgSuccess("入库成功");
        this.getList();
      })
    },
    //起始地和结束
    handleClick(row){
      this.startAddress=row.startAddress;
      this.endAddress=row.endAddress;
      this.goView();
    },
    /** 查询物流记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.driverId=user.state.id;
      listLogistics(this.queryParams).then(response => {
        this.logisticsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        logisticsId: null,
        startAddress: null,
        endAddress: null,
        consigner: null,
        consignee: null,
        goodsId: null,
        goodsNum: null,
        transportType: null,
        startTime: null,
        endeTime: null,
        logisticsCompany: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        isFault: null,
        goodsType: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logisticsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物流记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const logisticsId = row.logisticsId || this.ids
      getLogistics(logisticsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物流记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.logisticsId != null) {
            updateLogistics(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLogistics(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const logisticsIds = row.logisticsId || this.ids;
      this.$modal.confirm('是否确认删除物流记录编号为"' + logisticsIds + '"的数据项？').then(function() {
        return delLogistics(logisticsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    pauseAnimation () {
      this.marker.pauseMove();
    },
    resumeAnimation () {
      this.marker.resumeMove();
    },
    stopAnimation () {
      this.marker.stopMove();
    },
    startAnimation () {
      this.marker.moveAlong(this.lineArr, {
        // 每一段的时长
        duration: 500,//可根据实际采集时间间隔设置
        // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
        autoRotation: true,
      });
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "c07f01e374f57044eed54b1c33087ba1",//安全密钥
      };
      AMapLoader.load({
        key: "47c6eefcabdd8058080bc4fd263f1ea6", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.ToolBar', 'AMap.Driving', 'AMap.AutoComplete',"AMap.Scale", "AMap.ToolBar", "AMap.ControlBar", 'AMap.Geocoder', 'AMap.Marker',
          'AMap.CitySearch', 'AMap.Geolocation', 'AMap.InfoWindow'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
          });

        })
        .catch((e) => {
          console.log(e);
        });

    },




    goView() {
      // eslint-disable-next-line no-undef
      const driving = new AMap.Driving({
        map: this.map,
        // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
        // eslint-disable-next-line no-undef
        policy: AMap.DrivingPolicy.LEAST_TIME
      })
      //将城市范围划分在中国内
      const points = [
        { keyword: this.startAddress, city: '全国' },
        { keyword: this.endAddress, city: '全国' }
      ]

      driving.search(points, (status, result) => {
        // 未出错时，result即是对应的路线规划方案
        console.log('status=', status)
        console.log('result=', result)
      })

      // 运用小车图片以及起始地
      this.marker = new AMap.Marker({
        position: [0],
        icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
        offset: new AMap.Pixel(-13, -26),
      });
      this.map.add(this.marker)

      // 绘制轨迹
      this.polyline = new AMap.Polyline({
        path: this.points,
        showDir: true,
        strokeColor: "#28F",  //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6,      //线宽
        // strokeStyle: "solid"  //线样式
      });
      this.map.add(this.polyline)

      // 走过的路径
      this.passedPolyline = new AMap.Polyline({
        strokeColor: "#AF5",  //线颜色
        strokeWeight: 6,      //线宽
      });
      this.map.add(this.passedPolyline)

      // 监听marker小汽车移动
      this.marker.on('moving', (e) => {
        console.log('marker动了', e)
        this.passedPolyline.setPath(e.passedPath); // 设置路径样式
        this.map.setCenter(e.target.getPosition(), true) // 设置地图中心点
      });
      this.map.setFitView(); // 根据覆盖物自适应展示地图

    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/logistics/export', {
        ...this.queryParams
      }, `logistics_${new Date().getTime()}.xlsx`)
    },



  },
  mounted() {
    this.initAMap()
  },
  unmounted() {
    this.map?.destroy();
  },
};
</script>
<style scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 450px;
}
.input-item {
  height: 2.2rem;
}

.input-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: .25rem;
  width: 10rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, .5);
  position: fixed;
  bottom: 12rem;
  right: 2rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}
</style>
